package cn.wolfcode.trip.api.controller;

import cn.wolfcode.trip.api.controller.socket.WebSocketService;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.util.JsonResult;
import cn.wolfcode.trip.base.util.UserContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * WebSocketController class
 *
 * @author lishuanwang
 * @date 2019/5/31
 */
@Controller
@RequestMapping("messages")
public class WebSocketController  {
    /**
     *  websocket服务层的调用.
     */
    @Autowired
    private WebSocketService webSocketService;

    private Logger logger = LoggerFactory.getLogger(WebSocketController.class);

    /**
     * 发送消息
     * @param receiverId
     * @param message
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "user/{userId}", method = RequestMethod.GET)
    public JsonResult testWebSocket(@PathVariable Long userId,@RequestParam(value = "receiverId") Long receiverId,
                                @RequestParam(value = "message") String message, Long type){
        logger.debug("收到发送请求向用户{}的消息：{}",userId,message);

        JsonResult result = new JsonResult();
        if (!StringUtils.hasLength(message)){
            result.mark("发送的内容不能为空");
            return result;
        }
        if(webSocketService.sendToAllTerminal(userId, receiverId, message, type)){
           return result;
        }else{
            result.mark("对方不在线,我们已经转发给该用户");
          return result;
        }
    }

    @ResponseBody
    @GetMapping("user/{userId}/checkStatus")
    public JsonResult testUserStatus(@PathVariable Long userId){
        JsonResult result = new JsonResult();
        if (!webSocketService.checkUserStatus(userId)){
            result.mark("用户不在线");
        }
        return result;
    }

    @ResponseBody
    @GetMapping("groups/{groupId}")
    public JsonResult toGroupMessage(@PathVariable Long groupId,@RequestParam Long userId,
                                    @RequestParam(value = "message") String message){
        logger.debug("收到发送请求向群组{}的消息：{}",groupId,message);

        JsonResult result = new JsonResult();
        if (!StringUtils.hasLength(message)){
            result.mark("发送的内容不能为空");
            return result;
        }
        if(webSocketService.sendToGroup(userId, groupId, message)){
            return result;
        }
        return result;
    }


}
